package com.fire.control.system.module.company.service.impl;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import javax.transaction.Transactional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.fire.control.system.entity.Company;
import com.fire.control.system.entity.User;
import com.fire.control.system.module.company.dao.ManagementRepository;
import com.fire.control.system.module.company.service.IChargePersonService;
import com.fire.control.system.module.device.dao.ChargePersonRepository;
import com.fire.control.system.statics.Message_Response;
import com.fire.control.system.statics.ResponseMessage;
import com.fire.control.system.support.protocol.comman.ProtocolSelector;
import com.fire.control.system.support.protocol.comman.ResponseProtocol;
import com.fire.control.system.support.protocol.user.CpRequestProtocol;
import com.fire.control.system.support.util.XdaoDate;

/**
 * @author liuxincheng
 * @ClassName: ChargePersonServiceImpl
 * @Description: TODO(负责人业务实现)
 * @date 2017年5月11日 上午9:33:11
 */
@Service
public class ChargePersonServiceImpl implements IChargePersonService {
	@Autowired
	private ChargePersonRepository chargePersonRepository;

	@Autowired
	private ManagementRepository companyRepositoty;

	@Autowired
	private ProtocolSelector protocolSelector;

	/**
	 * <p>
	 * Title: getChargePersonList
	 * </p>
	 * <p>
	 * Description: 获得负责人列表
	 * </p>
	 * 
	 * @param requestProtocol
	 * @param p
	 * @return
	 * @see com.fire.control.system.module.company.service.IChargePersonService#getChargePersonList(com.fire.control.system.support.protocol.user.CpRequestProtocol,
	 *      org.springframework.data.domain.Pageable)
	 */
	@Override
	public ResponseProtocol getChargePersonList(CpRequestProtocol requestProtocol, Pageable p) {
		ResponseProtocol response = protocolSelector.choose(requestProtocol);

		Page<User> userPage = chargePersonRepository.findAll(p);

		if (!userPage.equals(null)) {
			ResponseMessage.CODE_200.messageToProtocol(response);
			response.setData(userPage);
			response.setIsSuccess(true);
			response.setDate(new XdaoDate());
			response.setMessage("数据返回成功!");
		} else {
			Message_Response.FAIL.messageToProtocol(response);
			response.setData(null);
			response.setIsSuccess(false);
			response.setDate(new XdaoDate());
			response.setMessage("数据返回失败!");
		}
		return response;
	}

	/**
	 * <p>
	 * Title: getListByCondition
	 * </p>
	 * <p>
	 * Description: 根据条件模糊查询负责人列表
	 * </p>
	 * 
	 * @param requestProtocol
	 * @param p
	 * @return
	 * @see com.fire.control.system.module.company.service.IChargePersonService#getListByCondition(com.fire.control.system.support.protocol.user.CpRequestProtocol,
	 *      org.springframework.data.domain.Pageable)
	 */
	@Override
	public ResponseProtocol getListByCondition(CpRequestProtocol requestProtocol, Pageable p) {
		ResponseProtocol response = protocolSelector.choose(requestProtocol);

		Page<User> companyPage = chargePersonRepository.findAll(new Specification<User>() {
			/**
			 * <p>
			 * Title: toPredicate
			 * </p>
			 * <p>
			 * Description:带条件的分页查询
			 * </p>
			 * 
			 * @param root
			 * @param query
			 * @param cb
			 * @return
			 * @see org.springframework.data.jpa.domain.Specification#toPredicate(javax.persistence.criteria.Root,
			 *      javax.persistence.criteria.CriteriaQuery,
			 *      javax.persistence.criteria.CriteriaBuilder)
			 */
			@Override
			public Predicate toPredicate(Root<User> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
				// TODO Auto-generated method stub
				List<Predicate> predicateList = new ArrayList<Predicate>();
				int statu = 0;
				String personName = requestProtocol.getName();
				boolean status = requestProtocol.isStatus();

				if (!StringUtils.isEmpty(personName)) {
					predicateList.add(cb.like(root.get("name").as(String.class), "%" + personName + "%"));
				}

				if (!StringUtils.isEmpty(status)) {
					if (status) {
						statu = 1;
						predicateList.add(cb.equal(root.get("status").as(Integer.class), statu));
					} else {
						statu = 0;
						predicateList.add(cb.equal(root.get("status").as(Integer.class), statu));
					}

				}

				query.orderBy(cb.desc(root.get("id").as(String.class)));

				Predicate[] predicates = new Predicate[predicateList.size()];
				predicates = predicateList.toArray(predicates);
				query.where(cb.and(predicates));
				return cb.and(predicates);
			}
		}, this.buildPageRequest(p.getPageNumber(), p.getPageSize()));

		if (!companyPage.getContent().isEmpty()) {
			ResponseMessage.CODE_200.messageToProtocol(response);
			response.setDate(new XdaoDate());
			response.setData(companyPage);
		} else {
			Message_Response.FAIL.messageToProtocol(response);
			response.setDate(new XdaoDate());
			response.setData(companyPage);
		}
		return response;
	}

	/**
	 * @author liuxincheng
	 * @Title: buildPageRequest
	 * @Description: TODO(构建分页请求)
	 * @param @param
	 *            pageNumber
	 * @param @param
	 *            pagzSize
	 * @param @return
	 *            设定文件
	 * @return PageRequest 返回类型
	 * @throws null
	 */
	private PageRequest buildPageRequest(int pageNumber, int pagzSize) {
		return new PageRequest(pageNumber - 1, pagzSize, null);
	}

	/**
	 * <p>
	 * Title: saveChagePerson
	 * </p>
	 * <p>
	 * Description: 保存负责人
	 * </p>
	 * 
	 * @param requestProtocol
	 * @return
	 * @see com.fire.control.system.module.company.service.IChargePersonService#saveChagePerson(com.fire.control.system.support.protocol.user.CpRequestProtocol)
	 */
	@Override
	public ResponseProtocol saveChagePerson(CpRequestProtocol requestProtocol) {
		ResponseProtocol response = protocolSelector.choose(requestProtocol);

		Company c = companyRepositoty.findOne(requestProtocol.getCompanyId());
		User u = requestProtocol.getUser();

		u.setCompany(c);
		User returnUser = chargePersonRepository.saveAndFlush(u);

		if (!returnUser.equals(null)) {
			ResponseMessage.CODE_200.messageToProtocol(response);
			response.setDate(new XdaoDate());
			response.setData(returnUser);
		} else {
			Message_Response.FAIL.messageToProtocol(response);
			response.setDate(new XdaoDate());
			response.setData(null);
		}
		return response;
	}

	/**
	 * <p>
	 * Title: updateChagePerson
	 * </p>
	 * <p>
	 * Description: 修改负责人信息
	 * </p>
	 * 
	 * @param requestProtocol
	 * @return
	 * @see com.fire.control.system.module.company.service.IChargePersonService#updateChagePerson(com.fire.control.system.support.protocol.user.CpRequestProtocol)
	 */
	@Override
	public ResponseProtocol updateChagePerson(CpRequestProtocol requestProtocol) {
		User u = null;
		ResponseProtocol response = protocolSelector.choose(requestProtocol);

		for (String id : requestProtocol.getId()) {
			u = chargePersonRepository.findOne(id);
		}
		Company c = companyRepositoty.findOne(requestProtocol.getCompanyId());
		User updateUser = requestProtocol.getUser();

		u.setUser(updateUser);
		u.setCompany(c);

		User returnUser = chargePersonRepository.saveAndFlush(u);

		if (!returnUser.equals(null)) {
			ResponseMessage.CODE_200.messageToProtocol(response);
			response.setDate(new XdaoDate());
			response.setData(returnUser);
		} else {
			Message_Response.FAIL.messageToProtocol(response);
			response.setDate(new XdaoDate());
			response.setData(null);
		}
		return response;
	}

	/**
	 * <p>
	 * Title: deleteChagePerson
	 * </p>
	 * <p>
	 * Description: 删除选中负责人
	 * </p>
	 * 
	 * @param requestProtocol
	 * @return
	 * @see com.fire.control.system.module.company.service.IChargePersonService#deleteChagePerson(com.fire.control.system.support.protocol.user.CpRequestProtocol)
	 */
	@Override
	public ResponseProtocol deleteChagePerson(CpRequestProtocol requestProtocol) {
		// TODO Auto-generated method stub
		ResponseProtocol response = protocolSelector.choose(requestProtocol);
		int n =0;
		User deletePerson = null;
		String[] ids = requestProtocol.getId();
		List<String> idList = Arrays.asList(ids);

		List<User> personList = chargePersonRepository.findAll(idList);

		for (User u : personList) {
			u.setStatus(false);
			deletePerson = chargePersonRepository.saveAndFlush(u);
			n++;
		}
		
		if(n<=0){
			Message_Response.FAIL.messageToProtocol(response);
			response.setDate(new XdaoDate());
			response.setData(null);
		}else{
			ResponseMessage.CODE_200.messageToProtocol(response);
			response.setDate(new XdaoDate());
			response.setData(deletePerson);
		}
		return response;
	}

	/**
	 * <p>
	 * Title: switchChagePerson
	 * </p>
	 * <p>
	 * Description: 转换负责人状态
	 * </p>
	 * 
	 * @param requestProtocol
	 * @return
	 * @see com.fire.control.system.module.company.service.IChargePersonService#switchChagePerson(com.fire.control.system.support.protocol.user.CpRequestProtocol)
	 */
	@Override
	@Transactional
	public ResponseProtocol switchChagePerson(CpRequestProtocol requestProtocol) {
		User u = null;
		ResponseProtocol response = protocolSelector.choose(requestProtocol);

		for (String id : requestProtocol.getId()) {
			u = chargePersonRepository.findOne(id);
		}
		Company c = companyRepositoty.findOne(requestProtocol.getCompanyId());
		u.setStatus(requestProtocol.isStatus());
		u.setCompany(c);

		User returnUser = chargePersonRepository.saveAndFlush(u);

		if (!returnUser.equals(null)) {
			ResponseMessage.CODE_200.messageToProtocol(response);
			response.setDate(new XdaoDate());
			response.setData(returnUser);
		} else {
			Message_Response.FAIL.messageToProtocol(response);
			response.setDate(new XdaoDate());
			response.setData(null);
		}
		return response;
	}
}
